const bcrypt = require('bcrypt')
const {Sequelize, Model} = require('sequelize')
const {sequelize} = require('../../core/db')

class User extends Model {
  static async verifyEmailPassword(email, plainPassword) {
    const user = await User.findOne({
      where: {
        email
      }
    })
    if(!user) {
      throw new global.errs.ParameterException('用户不存在')
      // throw new global.errs.ParameterException('用户不存在')
    }
    const correct = await bcrypt.compareSync(plainPassword, user.password) 
    if(!correct) {
      throw new global.errs.AuthFailed('密码不正确')
    }
    return user
  } 
  
  static async getUserByOpenId(openid) {
   const user = await User.findOne({
     where: {
       openid: openid
     }
   })
   return user
  }

  static async registerByOpenid(openid) {
    return await User.create({
      openid
    })
  }

} 

User.init({
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  nickname: Sequelize.STRING,
  email: Sequelize.STRING,
  password: {
    type: Sequelize.STRING,
    set(val) {
      // 设计模式 观察者模式
      // ES6 Reflect
      // const v = await new RegisterValidate().validate(ctx)
      const salt = bcrypt.genSaltSync(10)
      // 10表示花费的成本
      const psw = bcrypt.hashSync(val, salt)
      this.setDataValue('password', psw)
    }
  },
  openid: {
    type: Sequelize.STRING(64),
    unique: true
  }
}, {
  sequelize,
  tableName: 'user'
})

// 数据迁移 Sql 更新 但是会有风险


module.exports = User
